/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.shipdream.lib.ohos.mvc;

import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.ability.fraction.FractionAbility;
import ohos.aafwk.ability.fraction.FractionScheduler;
import ohos.agp.utils.TextTool;

import java.util.*;

/**
 * FragmentManager.
 *
 * @author a
 * @version v
 */
public class FragmentManager implements FragmentTransaction.TransactionListener {
    /**
     * POP_BACK_STACK_INCLUSIVE.
     */
    public static final int POP_BACK_STACK_INCLUSIVE = 1 << 0;
    private FractionAbility fractionAbility;

    private String currentTag;

    private LinkedHashMap<Fraction, BackStackEntry> fragmentQueue = new LinkedHashMap();

    public FragmentManager(FractionAbility fractionAbility) {
        this.fractionAbility = fractionAbility;
    }

    /**
     * findFragmentByTag .
     *
     * @param tag tag
     * @return Fraction
     */
    public Fraction findFragmentByTag(String tag) {
        Optional<Fraction> optional = fractionAbility.getFractionManager().getFractionByTag(tag);
        if (optional.isPresent()) {
            return optional.get();
        }
        return null;
    }

    /**
     * beginTransaction .
     *
     * @return FragmentTransaction
     */
    public FragmentTransaction beginTransaction() {
        FractionScheduler fractionScheduler = fractionAbility.getFractionManager().startFractionScheduler();
        FragmentTransaction fragmentTransaction = new FragmentTransaction(fractionScheduler, this);
        return fragmentTransaction;
    }

    /**
     * hideCurrent .
     */
    public void hideCurrent() {
        if (TextTool.isNullOrEmpty(currentTag)) {
            return;
        }
        Optional<Fraction> fractionByTag = fractionAbility.getFractionManager().getFractionByTag(currentTag);
        if (fractionByTag.isPresent()) {
            FractionScheduler fractionScheduler = fractionAbility.getFractionManager().startFractionScheduler();
            fractionScheduler.hide(fractionByTag.get());
            fractionScheduler.submit();
        }
    }

    /**
     * popBackStack .
     *
     * @param name  name
     * @param flags flags
     */
    public void popBackStack(final String name, final int flags) {
        Optional<Fraction> optional = fractionAbility.getFractionManager().getFractionByTag(name);
        if (!optional.isPresent()) {
            return;
        }
        FractionScheduler fractionScheduler = fractionAbility.getFractionManager().startFractionScheduler();
        Fraction fraction = optional.get();
        List<Fraction> fragments = getFragments();
        int index = fragments.indexOf(fraction);
        for (int j = index + 1; j < fragments.size(); j++) {
            Fraction remFraction = fragments.get(j);
            fractionScheduler.remove(remFraction);
            fragmentQueue.remove(remFraction);
        }
        fractionScheduler.show(fraction);
        fractionScheduler.submit();
        this.currentTag = name;

    }

    /**
     * popBackStack.
     */
    public void popBackStack() {
        List<Fraction> fragments = getFragments();
        if (!fragments.isEmpty()) {
            Fraction fraction = fragments.get(fragments.size() - 1);
            FractionScheduler fractionScheduler = fractionAbility.getFractionManager().startFractionScheduler();
            fractionScheduler.remove(fraction);
            fractionScheduler.submit();
            fragmentQueue.remove(fraction);
        }
        List<Fraction> fragments2 = getFragments();
        if (!fragments2.isEmpty()) {
            Fraction fraction = fragments2.get(fragments2.size() - 1);
            FractionScheduler fractionScheduler = fractionAbility.getFractionManager().startFractionScheduler();
            fractionScheduler.show(fraction);
            fractionScheduler.submit();
            String name = fragmentQueue.get(fraction).name;
            this.currentTag = name;
        }
    }

    /**
     * getFragments .
     *
     * @return List<Fraction>
     */
    public List<Fraction> getFragments() {
        ArrayList<Fraction> list = new ArrayList<>();
        Set<Map.Entry<Fraction, BackStackEntry>> entries = fragmentQueue.entrySet();
        Iterator<Map.Entry<Fraction, BackStackEntry>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<Fraction, BackStackEntry> next = iterator.next();
            Fraction key = next.getKey();
            list.add(key);
        }
        return list;
    }

    /**
     * getBackStackEntryCount .
     *
     * @return int
     */
    public int getBackStackEntryCount() {
        return fragmentQueue.size();
    }

    /**
     * getBackStackEntryAt .
     *
     * @param index index
     * @return BackStackEntry
     */
    public BackStackEntry getBackStackEntryAt(int index) {
        ArrayList<BackStackEntry> list = new ArrayList<>();
        Set<Map.Entry<Fraction, BackStackEntry>> entries = fragmentQueue.entrySet();
        Iterator<Map.Entry<Fraction, BackStackEntry>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<Fraction, BackStackEntry> next = iterator.next();
            BackStackEntry value = next.getValue();
            list.add(value);
        }
        return list.get(index);
    }


    @Override
    public void replaceListener(BackStackEntry backStackEntry) {
        this.currentTag = backStackEntry.name;
        fragmentQueue.put(backStackEntry.fraction, backStackEntry);
    }

    @Override
    public void removeListener(BackStackEntry backStackEntry) {
        fragmentQueue.remove(backStackEntry.fraction);
    }

    @Override
    public void commitListener() {

    }

    /**
     * BackStackEntry.
     */
    public static class BackStackEntry {
        private Fraction fraction;
        private String name;

        public BackStackEntry() {
        }

        public BackStackEntry(Fraction fraction, String name) {
            this.fraction = fraction;
            this.name = name;
        }

        public Fraction getFraction() {
            return fraction;
        }

        public void setFraction(Fraction fraction) {
            this.fraction = fraction;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
